﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SelfChain.Models;
using Newtonsoft.Json;
using YB.Mall.Utility;

namespace SelfChain.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            //TODO
            //区块链实现来完成工作量证明、权益证明这样的共识算法，或者是智能合约、Dapp、侧链

            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult BlockChain()
        {
            int blockChainCount = 0;
            Block newBlock = new Block();
            // 增加区块链
            if (BlockGenerator._blockChain.Count == 0)
            {
                Block firstBlock = new Block()
                {
                    Index = 0,
                    TimeStamp = BlockGenerator.CalculateCurrentTimeUTC(),
                    BPM = 0,
                    Hash = string.Empty,
                    PrevHash = string.Empty
                };
                BlockGenerator._blockChain.Add(firstBlock);
                newBlock = firstBlock;
                blockChainCount = 0;
            }
            else
            {
                int bpm= RandomUtil.GenerateRandom_Num(6);
                Block oldBlock = BlockGenerator._blockChain.Last();
                newBlock = BlockGenerator.GenerateBlock(oldBlock, bpm);

                if (BlockGenerator.IsBlockValid(newBlock, oldBlock))
                {
                    List<Block> newBlockChain = new List<Block>();
                    foreach (var block in BlockGenerator._blockChain)
                    {
                        newBlockChain.Add(block);
                    }

                    newBlockChain.Add(newBlock);
                    BlockGenerator.SwitchChain(newBlockChain);
                }
                blockChainCount = BlockGenerator._blockChain.Last().Index;
            }
            ViewBag.CurrentChains = JsonConvert.SerializeObject(newBlock);
            ViewBag.BlockChainCount = blockChainCount;
            return View();
        }


        public IActionResult BlockChains()
        {
            ViewData["ListChains"] = JsonConvert.SerializeObject(BlockGenerator._blockChain);
            return View();
        }
    }
}
